from rest_framework.parsers import BaseParser
from django.conf import settings
from rest_framework.settings import api_settings
import codecs
from rest_framework.exceptions import ParseError
from django.utils import six
from .xmltool import xml_to_dict
from rest_framework.utils import json


class XmlParser(BaseParser):
    media_type = 'text/xml'
    strict = api_settings.STRICT_JSON

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as a URL encoded form,
        and returns the resulting QueryDict.
        """
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)
            s = decoded_stream.read()
            print(type(s))
            return xml_to_dict(s)
        except ValueError as exc:
            raise ParseError('XML parse error - %s' % six.text_type(exc))